import json
import requests
from requests import RequestException
import riskPoints


def get_key():
    path = '../data/apikey.json'
    jsonfile = open(path, encoding='utf-8')

    datalist = json.load(jsonfile)
    key = datalist[0]['key']
    return key


def request_url_get(url, params=None):
    try:
        r = requests.get(url=url, params=params, timeout=30)
        if r.status_code == 200:
            return r.text
        print(r.status_code)
        return None
    except RequestException:
        print('error request')
        return None

def request_url_post(url, data):
    try:
        r = requests.post(url=url, data=data, timeout=30)
        if r.status_code == 200:
            return r.text
        print(r.status_code)
        return None
    except RequestException:
        print('error request')
        return None


def request_api(url, idx, params=None):
    if idx == 0:
        res = request_url_get(url, params)
    else:
        res = request_url_post(url, params)
    res = json.loads(res)
    return res


def get_coordinate_by_name(name):
    params = {
        'city': '北京市',
        'address': name,
        'key': get_key()
    }
    url = 'https://restapi.amap.com/v3/geocode/geo?parameters'
    res = request_api(url, 0, params)
    lng, lat = res['geocodes'][0]['location'].split(',')[0], res['geocodes'][0]['location'].split(',')[1]
    return lng, lat


def get_vertexes_of_coordinate(lng, lat):
    # 1m = 1 / 87642
    area_len = 1.0 / 87642 * 300
    lu = str(lng - area_len / 2) +  ', ' + str(lat + area_len / 2)
    ld = str(lng - area_len / 2) +  ', ' + str(lat - area_len / 2)
    rd = str(lng + area_len / 2) +  ', ' + str(lat - area_len / 2)
    ru = str(lng + area_len / 2) +  ', ' + str(lat + area_len / 2)
    return ';'.join([lu, ld, rd, ru])


def get_avoidpolygons(origin: tuple, destination: tuple):
    # 1m = 1 / 87642
    area_len = 1.0 / 87642 * 1000
    datalist = riskPoints.get_riskPoints_by_days(14)
    datalist = json.loads(datalist)
    datalist = sorted(datalist, key=lambda x: x['endTime'])

    origin = (float(origin[0]), float(origin[1]))
    destination = (float(destination[0]), float(destination[1]))

    left_border = min(origin[0], destination[0]) - area_len
    right_border = max(origin[0], destination[0]) + area_len
    top_border = max(origin[1], destination[1]) + area_len
    bottom_border = min(origin[1], destination[1]) - area_len

    def judge_in_area(lng, lat):
        if left_border <= lng <= right_border and bottom_border <= lat <= top_border:
            return True
        return False

    tmplist = []
    for data in datalist:
        if judge_in_area(data['lng'], data['lat']):
            tmplist.append((data['lng'], data['lat']))
    
    datalist = tmplist

    if len(datalist) > 32:
        datalist = datalist[:32]
    # datalist = datalist[:1]

    avoidpolygons = []
    for lng, lat in datalist:
        avoidpolygons.append(get_vertexes_of_coordinate(lng, lat))
    
    return avoidpolygons
    

def get_path_avoid_riskpoints(origin: str, destination: str, orilng=None, orilat=None, deslng=None, deslat=None, deslon=None):
    if orilng is None and orilat is None:
        orilng, orilat = get_coordinate_by_name(origin)
    if deslng is None and deslat is None:
        deslng, deslat = get_coordinate_by_name(destination)

    params = {
        'key': get_key(),
        'origin': orilng + ',' + orilat,
        'destination': deslng + ',' + deslat,
        'avoidpolygons': '|'.join(get_avoidpolygons((orilng, orilat), (deslng, deslat))),
        'show_fields': 'polyline'
    }
    print()
    url = 'https://restapi.amap.com/v5/direction/driving?parameters'

    res = request_api(url, 1, params)['route']['paths']
    print('avoid', params['avoidpolygons'])
    polyline = []
    d = res[0]
    s = d['steps']
    for j in s:
        pointlist = j['polyline'].split(';')
        for point in pointlist:
            polyline.append(point)

    polyline = {"polyline": polyline}
    polyline = json.dumps(polyline, ensure_ascii=False)
    return polyline

if __name__ == "__main__":
    # print(get_coordinate_by_name('双峪站'))
    # lng, lat = get_coordinate_by_name('双峪站')
    # print(get_vertexes_of_coordinate(116, 39))
    datalist = get_path_avoid_riskpoints('三里屯外交公寓', '工体北路世贸国际中心')
    print(datalist)
    # for d in datalist:
    #     s = d['steps']
    #     for j in s:
    #         print(j['polyline'])
    pass
